// File : form_validation.js

// Returns true if user has filled the input form acceptably.
// Otherwise, returns false.
function validate_input()
{
    var radio_buttons = document.getElementsByName("language_name");
    var n = radio_buttons.length;
    var selected_rb = false;
    for (var i = 0; i < n; i++)
    {
        var radio_button = radio_buttons[i];
        if (radio_button.checked)
            selected_rb = true;
    }
    if (!selected_rb)
    {
        alert ("Please select a language!");
        return false;
    }
    
    var tb_length = document.getElementsByName("length")[0];
    var s_length = tb_length.value;
    if (!validate_integer(s_length, 1, 100))
    {
        alert("Please enter text length (1 ... 100)!");
        return false;
    }
    
    var tb_paragraph_length = document.getElementsByName("paragraph_length")[0];
    var s_paragraph_length = tb_paragraph_length.value;
    if (!validate_integer(s_paragraph_length, 0, 20))
    {
        alert("Please enter paragraph length (0 ... 20)!");
        return false;
    }
    
    return true;
}

// Returns true if string s_input evaluates to an integer
// in the interval [i_min, i_max].
// Otherwise, returns false.
function validate_integer(s_input, i_min, i_max)
{
    var character_count = s_input.length;
    if (character_count == 0)
        return false;
        
    var allowed_characters = "+-0123456789";
    for (var i = 0; i < character_count; i++)
    {
        var character = s_input.substring(i, 1);
        if (allowed_characters.indexOf(character) < 0)
            return false;
    }
    
    var number = parseInt(s_input);
    if (number < i_min)
        return false;
    if (number > i_max)
        return false;
        
    return true; 
}